package EnterpriseAlgorithm.Stack_Queue.Code.StackWithGetMin;

import java.util.Stack;

class MyStack2 {
    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;

    public MyStack2() {
        this.stackData = new Stack<Integer>();
        this.stackMin = new Stack<Integer>();
    }
    public void push(int newNum) {
        if (this.stackMin.isEmpty()) { //stackMin为空直接压入，作为当前最小
            this.stackMin.push(newNum);
        } else if (newNum < this.getMin()) {  // newNum < stackMin.peek()时，就要让getMain栈顶元素更新了
            this.stackMin.push(newNum);
        } else{
            int newMin = this.stackMin.peek();// newNum >= stackMin.peek()时，就要让getMain栈顶元素继续沿用上次最小
            this.stackMin.push(newMin);
        }
        this.stackData.push(newNum);  // 元素是一定要stackData
    }
    public int pop() {
        if (this.stackData.isEmpty()) {
            throw new RuntimeException("Your stack is empty.");
        }
        this.stackMin.pop();  //同步弹出
        return this.stackData.pop();
    }
    public int getMin() {
        if (this.stackMin.isEmpty()) {
            throw new RuntimeException("Your stack is empty.");
        }
        return this.stackMin.peek();// getMin 栈顶元素保存目前栈内元素最小值
    }
}
